import asyncio
import json

from bilibili_api import Credential

from config import VIDEO_JSON_PATH, SESSDATA, BILI_JCT, BUVID3
from downloader import get_video_info
from bilibili_api.favorite_list import FavoriteList, get_video_favorite_list_content


async def load_video_json_async():
    with open(VIDEO_JSON_PATH, "r", encoding="utf-8") as f:
        video_json = json.load(f)
    video_bvs = video_json.get("video", [])
    video_infos = video_json.get("video_info", {})
    for bv in video_bvs:
        if bv in video_infos.keys():
            continue
        info = await get_video_info(bv)
        video_infos[bv] = {
            "title": info["title"],
            "owner": info["owner"]["name"]
        }
    video_json["video_info"] = video_infos
    with open(VIDEO_JSON_PATH, "w", encoding="utf-8") as f:
        json.dump(video_json, f)
    return video_bvs, video_infos


def load_video_json():
    return asyncio.get_event_loop().run_until_complete(load_video_json_async())

def add_bv_to_json(bv: str, index: int = 0):
    if index == 0:
        handle_bv = bv
    else:
        handle_bv = f"{bv}#{index}"
    try:
        info = asyncio.get_event_loop().run_until_complete(get_video_info(bv))
        with open(VIDEO_JSON_PATH, "r", encoding="utf-8") as f:
            video_json = json.load(f)
        video_bvs = video_json.get("video", [])
        if handle_bv in video_bvs:
            return False
        video_bvs.append(handle_bv)
        video_json["video"] = video_bvs
        video_infos = video_json.get("video_info", {})
        if index == 0:
            video_infos[handle_bv] = {
                "title": info["title"],
                "owner": info["owner"]["name"]
            }
        else:
            video_infos[handle_bv] = {
                "title": info["pages"][index]["part"],
                "owner": info["owner"]["name"]
            }
        video_json["video_info"] = video_infos
        with open(VIDEO_JSON_PATH, "w", encoding="utf-8") as f:
            json.dump(video_json, f)
        return True
    except Exception as e:
        print(e)
    return False


def load_bili_gather_video(media_id: int):
    credential = Credential(sessdata=SESSDATA, bili_jct=BILI_JCT, buvid3=BUVID3)
    favorite_list = FavoriteList(media_id=media_id, credential=credential)
    if not favorite_list.is_video_favorite_list():
        return load_video_json()
    content_video = asyncio.run(get_video_favorite_list_content(media_id))
    for key in content_video.keys():
        print(key)
        print(content_video[key])
    print(content_video['medias'][0])
    print(content_video['medias'][1])


if __name__ == '__main__':
    # add_bv_to_json("BV1LS4y1b7Kq")
    load_bili_gather_video(1363588646)
